package com.example.cloud.alibaba.seata.order.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.cloud.alibaba.seata.common.dto.AccountDTO;
import com.example.cloud.alibaba.seata.common.dto.OrderDTO;

import com.example.cloud.alibaba.seata.common.feign.IAccountService;
import com.example.cloud.alibaba.seata.common.utils.SimpleMessage;
import com.example.cloud.alibaba.seata.order.entity.TOrder;
import com.example.cloud.alibaba.seata.order.mapper.TOrderMapper;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * * @author lidong
 * @since 2019-09-04
 */
@Service
public class TOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> implements ITOrderService {

    @Autowired
    private IAccountService accountService;

    /**
     * 创建订单
     * @Param:  OrderDTO  订单对象
     * @Return:  OrderDTO  订单对象
     */
    @Override
    public SimpleMessage<OrderDTO> createOrder(OrderDTO orderDTO) {
        //扣减用户账户
        AccountDTO accountDTO = new AccountDTO();
        accountDTO.setUserId(orderDTO.getUserId());
        accountDTO.setAmount(orderDTO.getOrderAmount());
        SimpleMessage objectResponse = accountService.decreaseAccount(accountDTO);

        //生成订单号
        orderDTO.setOrderNo(UUID.randomUUID().toString().replace("-",""));
        //生成订单
        TOrder tOrder = new TOrder();
        BeanUtils.copyProperties(orderDTO,tOrder);
        tOrder.setCount(orderDTO.getOrderCount());
        tOrder.setAmount(orderDTO.getOrderAmount().doubleValue());
        try {
            baseMapper.createOrder(tOrder);
        } catch (Exception e) {
            return SimpleMessage.fail("创建订单失败");
        }

        if (objectResponse.getCode() != 200) {
            return SimpleMessage.fail("创建订单失败:"+objectResponse.getMessage());
        }
        return SimpleMessage.info(orderDTO);
    }

    @Override
    public SimpleMessage testAccount(String path) {
        return accountService.testAccount(path);
    }
}
